package com.jolink.omiis.wechat.redis;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.joinlink.omiis.commons.persistence.api.IDBProcessor;
import com.jolink.omiis.wechat.keys.IDBPreferences;
import com.jolink.omiis.wechat.keys.IPreferences;
import com.jolink.omiis.wechat.util.CacheUtil;
import com.jolink.omiis.wechat.util.DateUtil;
import com.jolink.omiis.wechat.util.GsonUtil;

import redis.clients.jedis.JedisPubSub;

public class JedisMessageListener extends JedisPubSub {

	@Autowired
	IRedisProcessor redis;

	@SuppressWarnings("rawtypes")
	@Autowired
	IDBProcessor dbProcessor;
	private static final Logger logger = LoggerFactory.getLogger(JedisMessageListener.class);

	@Override
	public void onMessage(String channel, String message) {
		long t1 = System.currentTimeMillis();
		logger.info("开始刷新配置信息，Channel：{}，Messgae：{}。", channel, message);
		if (IDBPreferences.JTOP_OM_PARAM_CONFIG.equalsIgnoreCase(message)) {
			loadOvertimeTipConfig();
		} else if (IDBPreferences.JTOP_OM_WORKDAY_INFO.equalsIgnoreCase(message)) {
			loadWorkDayConfig();
		}
		// loadWorkDayConfig();
		long t2 = System.currentTimeMillis();
		logger.info("刷新配置信息完成，耗时：{}毫秒。", t2 - t1);
	}

	private void loadWorkDayConfig() {
		long t1 = System.currentTimeMillis();
		String sql = "select id,calendar_date,begin_time,end_time,is_holiday from om_workday_info";
//		String sql = "select id,calendar_date,begin_time,end_time,is_holiday from om_workday_info  where begin_time is not null and end_time is not null";
		List<Map<String, Object>> result = null;
		try {
			result = dbProcessor.query(sql, new String[] {});
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		if (result == null || result.isEmpty()) {
			logger.error("加载工作时间配置失败！");
			return;
		}
		logger.info("开始清理工作时间缓存数据......");
		for (Map<String, Object> item : result) {
			String calendar_date = null;
			try {
				calendar_date = DateUtil.transfer2DateString((Timestamp) item.get("calendar_date"), "yyyyMMdd");
				if (logger.isDebugEnabled()) {
					logger.debug("清理日期：{}。", calendar_date);
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			if (StringUtils.isEmpty(calendar_date)) {
				continue;
			}
			try {
				redis.del(CacheUtil.getWorkDayKey(calendar_date));
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}

		logger.info("清理工作时间缓存数据完成，重新加载配置.....");
		Map<String, String> workDayMap = null;
		for (Map<String, Object> item : result) {
			String id = (String) item.get("id");
			String calendar_date = DateUtil.transfer2DateString((Timestamp) item.get("calendar_date"), "yyyyMMdd");
			workDayMap = new HashMap<>();
			item.put("updateTimestamp", DateUtil.getCurrentDate());
			workDayMap.put(id, GsonUtil.map2Json(item));
			try {
				redis.hmset(CacheUtil.getWorkDayKey(calendar_date), workDayMap);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
		long t2 = System.currentTimeMillis();
		logger.info("工作时间重新加载完成，耗时：{}毫秒。", (t2 - t1));
	}

	private void loadOvertimeTipConfig() {
		long t1 = System.currentTimeMillis();
		logger.info("开始加载超时提示语配置......");
		String sql = "select id,param_name,param_code,param_describe,param_value from om_param_config where status='1'";
		List<Map<String, Object>> result = null;
		try {
			result = dbProcessor.query(sql, new String[] {});
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		if (result == null || result.isEmpty()) {
			logger.error("管理台未配置超时提示语！");
			return;
		}
		for (Map<String, Object> item : result) {
			String param_code = (String) item.get("param_code");
			Map<String, String> config = new HashMap<String, String>();
			config.put(param_code, GsonUtil.map2Json(item));
			try {
				redis.hmset(IPreferences.OM_PARAM_CONFIG, config);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
		long t2 = System.currentTimeMillis();
		logger.info("加载超时提示语配置完成，耗时：{}毫秒。", (t2 - t1));
	}
}
